<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/20
 * Time: 11:00
 */
namespace App\Service\Api;

use App\Http\Model\Mysql\OrderModel;
use App\Http\Model\Mysql\OrderCommentModel;
use App\Http\Model\Mysql\OrderProductModel;
use App\Http\Model\Mysql\OrderRefundModel;
use App\Http\Model\Mysql\OrderRefundProcessModel;
use App\Http\Model\Mysql\UserAddressModel;
use Carbon\Carbon;

class MarketService extends BaseService
{
    /**
     * 用户申请退款
     * @param array $params     请求参数
     * @param string $order_number 订单号
     * @return array
     */
    public function marketRefund(array $params, string $order_number)
    {
        $user_info  =   request()->post('api_user');

        $order_info =   OrderModel::where(['order_no' => $order_number, 'user_id' => $user_info['user_id'], 'is_delete' => OrderModel::NOT_DELETE])->select(['id', 'user_id', 'order_no', 'pay_price', 'order_status', 'refund_status'])->first();

        if (empty($order_info)) {
            return [false, '订单不存在'];
        }

        if ($order_info->order_status == OrderModel::IS_AFTER_SALE || $order_info->refund_status != OrderModel::APPLY_NORMAL) {
            return [false, '订单售后处理中'];
        }
        /**
         * 订单状态修改
         */
        OrderModel::where(['id' => $order_info->id])->update(['order_status' => OrderModel::IS_AFTER_SALE, 'refund_status' => OrderModel::APPLY_REFUND]);

        /**
         * 售后记录保存
         */
        $order_refund['user_id']    =   $user_info['user_id'];
        $order_refund['order_id']   =   $order_info->id;
        $order_refund['detail_id']  =   $params['detail_id'];
        $order_refund['refund_no']  =   createRandomNumber(24);
        $order_refund['refund_type']=   OrderRefundModel::ONLY_REFUND;
        $order_refund['refund_price']=  OrderProductModel::where(['uid' => $user_info['user_id'], 'order_id' => $order_info->id, 'id' => $params['detail_id']])->value('product_total') ?? 0;
        $order_refund['reason']     =   $params['refund_reason'] ?? '';
        $order_refund['remark']     =   $params['refund_remark'] ?? '';
        $order_refund['proof']      =   json_encode($params['refund_proof'] ?? [], JSON_UNESCAPED_UNICODE);
        $order_refund['is_receive'] =   $params['is_receive'];

        $after_result   =   OrderRefundModel::create($order_refund);

        if ($after_result) {
            OrderRefundProcessModel::create([
                'refund_id'     =>  $after_result->id,
                'operate_user'  =>  0,
                'operate_time'  =>  Carbon::now()->timestamp,
                'operate_type'  =>  $order_refund['refund_type'],
                'operate_function'=>OrderRefundProcessModel::FUNCTION_APPLY,
                'operate_desc'  =>  '退款' . OrderRefundProcessModel::FUNCTION_DESC[OrderRefundProcessModel::FUNCTION_APPLY],
            ]);
            return [true, '申请成功'];
        }
        return [false, '申请失败'];
    }

    /**
     * 用户申请退货
     * @param array $params
     * @param string $order_number
     * @return array
     */
    public function marketReturn(array $params, string $order_number)
    {
        $user_info  =   request()->post('api_user');

        $order_info =   OrderModel::where(['order_no' => $order_number, 'user_id' => $user_info['user_id'], 'is_delete' => OrderModel::NOT_DELETE])->select(['id', 'user_id', 'order_no', 'pay_price', 'order_status', 'refund_status'])->first();

        if (empty($order_info)) {
            return [false, '订单不存在'];
        }

        if ($order_info->order_status == OrderModel::IS_AFTER_SALE || $order_info->refund_status != OrderModel::APPLY_NORMAL) {
            return [false, '订单售后处理中'];
        }
        /**
         * 订单状态修改
         */
        OrderModel::where(['id' => $order_info->id])->update(['order_status' => OrderModel::IS_AFTER_SALE, 'refund_status' => OrderModel::APPLY_RETURN]);

        /**
         * 售后记录保存
         */
        $order_return['user_id']    =   $user_info['user_id'];
        $order_return['order_id']   =   $order_info->id;
        $order_return['detail_id']  =   $params['detail_id'];
        $order_return['refund_no']  =   createRandomNumber(24);
        $order_return['refund_type']=   OrderRefundModel::ONLY_RETURN;
        $order_return['reason']     =   $params['refund_reason'] ?? '';
        $order_return['remark']     =   $params['refund_remark'] ?? '';
        $order_return['proof']      =   json_encode($params['refund_proof'] ?? [], JSON_UNESCAPED_UNICODE);
        $order_return['is_receive'] =   $params['is_receive'];
        $order_return['is_user_send']   =   $params['is_user_send'] ?? 0;
        $order_return['user_express']   =   $params['send_express'] ?? '';
        $order_return['user_express_no']=   $params['send_express_no'] ?? '';

        $after_result   =   OrderRefundModel::create($order_return);

        if ($after_result) {
            OrderRefundProcessModel::create([
                'refund_id'     =>  $after_result->id,
                'operate_user'  =>  0,
                'operate_time'  =>  Carbon::now()->timestamp,
                'operate_type'  =>  $order_return['refund_type'],
                'operate_function'=>OrderRefundProcessModel::FUNCTION_APPLY,
                'operate_desc'  =>  '退货' . OrderRefundProcessModel::FUNCTION_DESC[OrderRefundProcessModel::FUNCTION_APPLY],
            ]);
            return [true, '申请成功'];
        }
        return [false, '申请失败'];
    }

    /**
     * 用户申请换货
     * @param array $params
     * @param string $order_number
     * @return array
     */
    public function marketExchange(array $params, string $order_number)
    {
        $user_info  =   request()->post('api_user');

        $order_info =   OrderModel::where(['order_no' => $order_number, 'user_id' => $user_info['user_id'], 'is_delete' => OrderModel::NOT_DELETE])->select(['id', 'user_id', 'order_no', 'pay_price', 'order_status', 'refund_status'])->first();

        if (empty($order_info)) {
            return [false, '订单不存在'];
        }

        if ($order_info->order_status == OrderModel::IS_AFTER_SALE || $order_info->refund_status != OrderModel::APPLY_NORMAL) {
            return [false, '订单售后处理中'];
        }

        /**
         * 查看新的收货地址
         */
        $address_info   =   UserAddressModel::where(['id' => $params['address_id'], 'user_id' => $user_info['user_id'], 'is_delete' => UserAddressModel::NOT_DELETE])->select(['id', 'user_id', 'tel_number', 'user_name', 'province', 'city', 'address', 'area'])->first();
        if (empty($address_info)) {
            return [false, '地址存在'];
        }

        /**
         * 订单状态修改
         */
        $update_order['order_status']   =   OrderModel::IS_AFTER_SALE;
        $update_order['refund_status']  =   OrderModel::APPLY_RETURN;
        $update_order['buyer_name']     =   $address_info->user_name;
        $update_order['buyer_phone']    =   $address_info->tel_number;
        $update_order['buyer_province'] =   $address_info->province;
        $update_order['buyer_city']     =   $address_info->city;
        $update_order['buyer_area']     =   $address_info->area;
        $update_order['buyer_address']  =   $address_info->address;
        OrderModel::where(['id' => $order_info->id])->update($update_order);

        /**
         * 售后记录保存
         */
        $order_refuse['user_id']    =   $user_info['user_id'];
        $order_refuse['order_id']   =   $order_info->id;
        $order_refuse['detail_id']  =   $params['detail_id'];
        $order_refuse['refund_no']  =   createRandomNumber(24);
        $order_refuse['refund_type']=   OrderRefundModel::ONLY_REFUSE;
        $order_refuse['reason']     =   $params['refund_reason'] ?? '';
        $order_refuse['remark']     =   $params['refund_remark'] ?? '';
        $order_refuse['proof']      =   json_encode($params['refund_proof'] ?? [], JSON_UNESCAPED_UNICODE);
        $order_refuse['is_receive'] =   $params['is_receive'];
        $order_refuse['address_id'] =   $params['address_id'];
        $order_refuse['is_user_send']   =   $params['is_user_send'] ?? 0;
        $order_refuse['user_express']   =   $params['send_express'] ?? '';
        $order_refuse['user_express_no']=   $params['send_express_no'] ?? '';

        $after_result   =   OrderRefundModel::create($order_refuse);

        if ($after_result) {
            OrderRefundProcessModel::create([
                'refund_id'     =>  $after_result->id,
                'operate_user'  =>  0,
                'operate_time'  =>  Carbon::now()->timestamp,
                'operate_type'  =>  $order_refuse['refund_type'],
                'operate_function'=>OrderRefundProcessModel::FUNCTION_APPLY,
                'operate_desc'  =>  '退换货' . OrderRefundProcessModel::FUNCTION_DESC[OrderRefundProcessModel::FUNCTION_APPLY],
            ]);
            return [true, '申请成功'];
        }
        return [false, '申请失败'];
    }

    /**
     * 查看售后进度
     * @param string $order_number
     * @param int $detail_id
     * @return array
     */
    public function marketProcess(string $order_number, int $detail_id)
    {
        $user_info  =   request()->post('api_user');
        $order_info =   OrderModel::where(['order_no' => $order_number, 'user_id' => $user_info['user_id'], 'is_delete' => OrderModel::NOT_DELETE])->select(['id', 'user_id', 'order_no', 'pay_price', 'order_status', 'refund_status'])->first();

        if (empty($order_info)) {
            return [false, '订单不存在'];
        }

        if ($order_info->order_status != OrderModel::IS_AFTER_SALE || $order_info->refund_status == OrderModel::APPLY_NORMAL) {
            return [false, '订单未进行售后'];
        }

        $refund_info    =   OrderRefundModel::where(['user_id' => $user_info['user_id'], 'order_id' => $order_info->id, 'detail_id' => $detail_id, 'is_delete' => OrderRefundModel::NOT_DELETE])->select(['id', 'order_id', 'detail_id', 'refund_no', 'refund_type', 'refund_status', 'refund_price', 'reason', 'remark', 'response_time', 'address_id', 'created_at'])->first();
        if (empty($refund_info)) {
            return [false, '退款信息不存在'];
        }

        /**
         * 设置商城收货地址
         */
        $address_info['receive_name']     =   '网虹城产品部-阿祖';
        $address_info['receive_phone']    =   '18758265185';
        $address_info['receive_province'] =   '浙江省';
        $address_info['receive_city']     =   '杭州市';
        $address_info['receive_area']     =   '江干区';
        $address_info['receive_address']  =   '18号大街100号网虹城A幢1楼';

        $refund_info->response_time =   Carbon::createFromTimestamp($refund_info->response_time)->toDateTimeString();
        $refund_info->created_time  =   $refund_info->created_at->toDateTimeString();
        $refund_info->address_info  =   $address_info;
        $refund_info->process       =   OrderRefundProcessModel::where(['refund_id' => $refund_info['id']])->orderBy('operate_time', 'asc')->select(['refund_id', 'operate_time', 'operate_type', 'operate_desc', 'operate_function', 'operate_remark'])->get()->each(function (&$item) {
                                            $item->operate_time =   Carbon::createFromTimestamp($item->operate_time)->toDateTimeString();
                                        });
        unset($refund_info->created_at);
        return [true, $refund_info];
    }

    /**
     * 售后订单取消
     * @param string $refund_no
     * @return array
     */
    public function marketCancel(string $refund_no)
    {
        /**
         * 查看售后订单详情
         */
        $refund_info    =   OrderRefundModel::where(['refund_no' => $refund_no, 'is_delete' => OrderRefundModel::NOT_DELETE])->select(['id', 'order_id', 'detail_id', 'refund_type'])->first();
        if (empty($refund_info)) {
            return [false, '售后订单不存在'];
        }

        try {
            /**
             * 更改订单状态
             */
            OrderModel::where(['id' => $refund_info['order_id']])->update(['order_status' => OrderModel::IS_NORMAL, 'refund_status' => OrderModel::APPLY_NORMAL]);

            /**
             * 删除订单售后
             */
            OrderRefundModel::where(['id' => $refund_info['id']])->update(['is_delete' => OrderRefundModel::IS_DELETE, 'delete_time' => Carbon::now()->timestamp]);

            /**
             * 删除订单进度
             */
            OrderRefundProcessModel::where(['refund_id' => $refund_info['id']])->delete();

            return [true, '取消成功'];
        } catch (\Exception $exception) {
            return [false, $exception->getMessage()];
        }

    }

    /**
     * 售后订单详情
     * @param string $refund_no
     * @return array
     */
    public function marketDetail(string $refund_no)
    {
        /**
         * 查看售后订单详情
         */
        $refund_info    =   OrderRefundModel::where(['refund_no' => $refund_no, 'is_delete' => OrderRefundModel::NOT_DELETE])->select(['id', 'order_id', 'detail_id', 'refund_type', 'refund_status', 'refund_price', 'is_receive', 'proof', 'reason', 'is_user_send', 'user_express', 'user_express_no', 'refund_status', 'is_agree'])->first();
        if (empty($refund_info)) {
            return [false, '售后订单不存在'];
        }

        return [true, $refund_info->toArray()];
    }

    /**
     * 售后订单修改
     * @param array $params
     * @param string $refund_no
     * @return array
     */
    public function marketModify(array $params, string $refund_no)
    {
        $modify['reason']   =   $params['refund_reason'];
        $modify['is_receive']=  $params['is_receive'] ?? 0;
        $modify['proof']    =   json_encode($params['refund_proof'] ?? [], JSON_UNESCAPED_UNICODE);
        $modify['is_user_send']   =   $params['is_user_send'] ?? 0;
        $modify['user_express']   =   $params['send_express'] ?? '';
        $modify['user_express_no']=   $params['send_express_no'] ?? '';

        $update_result      =   OrderRefundModel::where(['refund_no' => $refund_no])->update($modify);
        if ($update_result) {
            return [true, '修改成功'];
        } else {
            return [false, '修改失败'];
        }
    }

}
